import {
  ds
} from 'data'

export const dsFiles = {
  chooseMedia: function (params) { // params: function | {count, mediaType, sourceType, ...}
    const that = this
    wx.chooseMedia({
      count: params?.count ?? 1,
      mediaType: params?.mediaType ?? ['image', 'video'],
      sourceType: params?.sourceType ?? ['album', 'camera'],
      success: (chooseResult) => {
        const tempFile = chooseResult.tempFiles[0].tempFilePath;
        if (typeof params == 'function') params(tempFile);
        else if (params?.success) params.success(tempFile);
      },
    })
  },
  uploadFile: function (tempFile, _folder, _cb) {
    const folder = (typeof _folder == 'string') ? (_folder + '/') : ''
    const cb = (typeof _folder == 'function') ? _folder : _cb

    const fileName = tempFile.substr(tempFile.lastIndexOf('/') + 1)
    wx.cloud.uploadFile({
      cloudPath: `${folder}${fileName}`,
      filePath: tempFile, // 文件路径
    }).then(res => {
      if (typeof cb == 'function') cb(res.fileID)
    }).catch(err => {
      console.log(err)
    })
  },
  insert2files(fileId, cb, tag) {
    const swiper = ds.coll('files')
    swiper.add({
      data: {
        fileId: fileId,
        tag
      },
      success: function (res) {
        if (cb) cb(fileId)
      },
      fail: function (err) {
        if (cb) cb(null, err)
        console.error(err)
      }
    });
  },
  delFromFiles(fileId) {
    const swiper = ds.coll('files')
    swiper.where({
      fileId: fileId
    }).remove();
  },
  isImage(pathName) {
    const supported = {
      "jpg": true,
      "jpeg": true,
      "png": true,
      "svg": true,
      "webp": true,
      "gif": true
    }
    return supported[this.ext(pathName).toLowerCase()] || false
  },
  isVideo(pathName) {
    const supported = {
      "mp4": true,
      "3gp": true,
      "m3u8": true
    }
    return supported[this.ext(pathName).toLowerCase()] || false
  },
  isSupported(pathName) {
    return this.isImage(pathName) || this.isVideo(pathName)
  },
  ext(pathName) {
    const idx = pathName.lastIndexOf('.')
    return pathName.substr(idx + 1)
  },
  name(pathName) {
    const idx = pathName.lastIndexOf('.')
    return pathName.substr(pathName.lastIndexOf('/') + 1, idx)
  },
  nameExt(pathName) {
    return pathName.substr(pathName.lastIndexOf('/') + 1)
  },
  descFileType(pathName) {
    if (this.isImage(pathName)) return "image"
    if (this.isVideo(pathName)) return "video"
    return "unsupported"
  },
  descFileTypeList(pathNameList) {
    const res = []
    for (const pathName of pathNameList) {
      res.push(this.descFileType(pathName))
    }
    return res
  }
}